﻿

using System;
using System.Linq;
using Demo.Domain;
using Demo.Repository;

namespace Demo.Repository
{
    public class UserRepository : IUserRepository
    {
        DemoContext db = new DemoContext();

        public User GetByName(string userName)
        {
            return db.User.Where(u => u.Name == userName).FirstOrDefault();
        }

        public bool ExistsWithUserName(string userName)
        {
            return db.User.Where(u => u.Name == userName).Count() > 0 ;
        }

        public bool Exists(string userName, string password)
        {
            return db.User.Where(u => u.Name == userName && u.Password == password).Count() > 0;
        }

        public void CreateUser(string userName, string password, int roleID)
        {
            var user = new User {  Name = userName, Password = password, RoleID = roleID};
            db.User.Add(user);
            db.SaveChanges();
        }

        public bool ChangePassword(string userName, string password, string newPassword)
        {
            var user = db.User.Where(u => u.Name == userName && u.Password == password).FirstOrDefault();
            if(user != null )
            {
                user.Password = newPassword;
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public bool ChangeRole(string userName, int roleID)
        {
            var user = db.User.Where(u => u.Name == userName ).FirstOrDefault();
            if (user != null)
            {
                user.RoleID = roleID;
                db.SaveChanges();
                return true;
            }
            return false;
        }

    }
}
